package com.zonski.jbots.desktop.editer.tool;

import com.zonski.jbots.game.EntityHelper;
import com.zonski.jbots.engine.Entity;
import com.zonski.jbots.engine.Rectangle;
import com.zonski.jbots.desktop.editer.AbstractMouseTool;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

/**
 * Created by IntelliJ IDEA.
 * User: Chris Glover
 * Date: Oct 27, 2003
 * Time: 1:04:21 PM
 * To change this template use Options | File Templates.
 */
public class CreateTool extends AbstractMouseTool
{
    private String toCreate;
    private int defaultLevel;

    public CreateTool(String toCreate, int defaultLevel)
    {
        this.toCreate = toCreate;
        this.defaultLevel = defaultLevel;
    }

    public MouseListener createMouseListener()
    {
        return new CreateMouseListener();
    }

    protected void doActivate()
    {
        super.doActivate();
        // set the default level for this entity type
        if(this.defaultLevel >= 0)
        {
            this.getContext().setCurrentLevel(this.defaultLevel);
        }
    }

    public void createAt(int x, int y)
    {
        try
        {
            Entity entity = this.getContext().getEntityFactory().createEntity(this.toCreate);
            if(this.getContext().isCentredOnTile())
            {
                EntityHelper.centreAtClosestTile(entity.bounds, new Rectangle(x, y, 1, 1), this.getContext().getRoom());
            }else{
                entity.bounds.setCentre(x, y);
            }
            entity.layerId = this.getContext().getCurrentLevel();
            this.getContext().getRoom().addEntity(entity);
            this.getContext().getComponent().repaint();
        }catch(Exception ex){
            getContext().showError("Couldn't create "+toCreate, ex);;
        }
    }

    private class CreateMouseListener extends MouseAdapter
    {
        public CreateMouseListener()
        {
        }

        public void mousePressed(MouseEvent event)
        {
            super.mousePressed(event);
            createAt(event.getX(), event.getY());
        }
    }
}
